﻿import kliment.events.Event;
import kliment.events.HTTPStatusEvent;
import kliment.net.URLMethod;
import kliment.utils._Object;
import mx.events.EventDispatcher;
import mx.utils.Delegate;
/**
 * ...
 * @author Kliment
 */
class kliment.net.URLLoader {
	private var _url:String = '';
	private var _conteinerLoad:LoadVars;
	private var _contentType:String;
	private var _isLoaded:Boolean = false;
	
	private var _data:String;
	
	public function URLLoader() {
		EventDispatcher.initialize(this);
		
	}
	
	private function _createConteiner():LoadVars {
		if (_conteinerLoad) {
			_conteinerLoad.onData = null;
			_conteinerLoad.onHTTPStatus = null;
			_conteinerLoad = null;;
		}
		_conteinerLoad = new LoadVars();
		if (_contentType) 
			_conteinerLoad.contentType = _contentType;
		_conteinerLoad.onData = Delegate.create(this, _onDataHandler);
		_conteinerLoad.onHTTPStatus = Delegate.create(this, _onHTTPStatusHandler);
		return _conteinerLoad;
	}
	
	public function load(url:String):Boolean {
		_isLoaded = false;
		_url = url;
		_createConteiner();
		return _conteinerLoad.load(_url);
	}
	
	public function sendAndLoad(url:String,  object:Object, method:String):Boolean {
		_isLoaded = false;
		_url = url;
		_createConteiner();
		var sendVars:LoadVars = new LoadVars();
		_Object.copyTo(object, sendVars);
		return sendVars.sendAndLoad(_url, _conteinerLoad, method || URLMethod.POST);
	}
	
	private function _onHTTPStatusHandler(httpStatus:Number):Void {
		dispatchEvent(new HTTPStatusEvent(HTTPStatusEvent.HTTP_STATUS, this, httpStatus));
	}
	
	private function _onDataHandler(src:String):Void {
		_isLoaded = true;
		_data = src;
		dispatchEvent(new Event(Event.COMPLETE, this));
	}
	
	public function get contentType():String { return _contentType; }
	public function set contentType(value:String):Void {
		_contentType = value;
	}
	
	public function getBytesLoaded():Number {
		return _conteinerLoad.getBytesLoaded();
	}
	
	public function getBytesTotal():Number {
		return _conteinerLoad.getBytesTotal();
	}
	
	public function get isLoaded():Boolean { return _isLoaded; }
	
	public function addEventListener(eventType:String, handler:Function):Void {  }
	
	public function dispatchEvent(event:Event):Void {  }
	
	public function removeEventListener(eventType:String, handler:Function):Void {  }
	
}